<?php

class Action_Quest_CreateQuest extends RL_Handler{
	/**
	* @var Model_Quest
	**/
	private $model;
	private $oQuest;
	private $step;
	private $view;
	private $saveError;
	private $days = Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
	private $doc_types = Array('doc','image','link','file','issue','review');
	private $actions = array();
	private $edit;
	const STEPS = 4;

	const RP_NONE=0;
	const RP_MODERATOR=9;
	const RP_MEMBER=12;
	const RP_ALL=15;

	const DATE_FOREVER = '2099-12-31';

	var $ajax_functions = array(
		'ajax_getUsersList',
		'ajax_getUserId',
	);

	public function init() {
		session_start();
		$this->rh->useClass("Model_Item");
		$this->model = $this->ctx->mm->getModel("Quest");
		$this->rh->UseClass('RL_URLGenerator');

		if($this->params['quest_step']){
			$this->step = intval($this->params['quest_step']);
		}else{
			$this->step = intval($this->rh->POST['step']);
		}

		if($this->params['quest_id']){
			$this->edit = true;
			$this->oQuest = $this->model->getItem($this->params['quest_id']);
		}else{
			if($this->step > 0)
				$questData = $_SESSION['create_quest_data'];
			else
				$questData = null;
			$this->oQuest = $this->model->createItem($questData);
			$this->edit = false;
		}

		if($this->step>3){
			$this->step = $this->oQuest->data['is_published']?4:3;
		}

        $roles = $this->model->getUserRole($this->oQuest);
        if(!$roles[Model_Quest::ROLE_GIVER])
            die("Access denited");

		$this->actions['edit'] = isset($this->rh->POST['step']);
		$this->actions['next'] = isset($this->rh->POST['next_x']);
		$this->actions['save'] = isset($this->rh->POST['save_x']);
		$this->actions['publish'] = isset($this->rh->POST['publish_x']);
		$this->actions['save'] = isset($this->rh->POST['save_x']) || $this->actions['publish'];
	}

	public function process() {
 		// -- old theme HACK : 2008-05-21 : lucky -- {{{
		$community_skin = 'platonica';
		$tpl = $this->ctx->tpl;
		$community_model = $this->ctx->mm->getModel("Community");
		$community_model->setDefaultSkin($community_skin);
		$tpl->setSkin($community_skin);
		$views_php = $tpl->findFile('', 'views', $tpl->_skin, 'php');
		unset ($config);
		include $views_php; // got $config
		$this->ctx->rh->views->setViewConfig($config);
		// -- old theme HACK : 2008-05-21 : lucky -- }}}

		$this->view = $this->rh->views->findByName('create_quest');
		$this->view->data = $this->module->aa->template_data;

		//просто публикация (ничего не сохраняя)
		if($this->actions['publish']) {
			$this->oQuest->data['is_published'] = 1;
		}
		//применение операций, сделанных в предыдущем шаге
		if($this->actions['edit']) {
			$method = "stepAction".($this->step);
			if(method_exists($this, $method)) {
				$this->$method();

				if(!$this->saveError) {
					//сохранение данных в БД
					if($this->actions['save']) {
					   if($this->edit) {
					       $this->model->upItem($this->oQuest);
						} else {
								$aa = $this->module->aa;
								// раздел, где создается квест.
								$parent_oid = $aa->acl_data['comity_oid'];
								$this->model->saveItem($this->oQuest, $parent_oid);
						}

						if(!$this->edit){
							$ug = new RL_URLGenerator($this->rh->router->getRule("edit_quest"));
							$ug->setRouter($this->rh->router);
							$ug->setParams(array(
								"community_url"	=> $this->params['community_url'],
								"quest_id"		=> $this->oQuest->id,
								"quest_step"	=> "0",
							));
							$this->rh->redirect($ug->generateUrl());
						}
					}
					//переход к след шагу
					if($this->actions['next']) {
						$this->step++;
						$_SESSION['create_quest_data'] = $this->oQuest->data;
					}
				}
			}
		}
		//отображение текущего шага
		$this->showSteps();
		$this->view->data['step'] = $this->step;
		$stepMethod = "showStep".$this->step;
		if(method_exists($this, $stepMethod)) {
			$this->$stepMethod();
		}

		$this->rh->response->setContent($this->view);
	}

	private function checkDate($date){
		$result = 0;
		if(preg_match('/^(\d{4})-(\d{2})-(\d{2})$/',$date, $res)){
			if((intval($res[1])>1999)&&(intval($res[1])<2100)&&(intval($res[2])<13)&&($res[2]>0)&&($res[3]>0)){
				$res[1]%4==0?$this->days[2]=29:$this->days[2]=28;
				if(intval($res[3])<=$this->days[intval($res[2])]){
					$result = 1;
				}
			}
		}
		return $result;
	}

	private function showSteps() {
		//кнопки панели
		$csteps = $this->oQuest->data['is_published']?self::STEPS:self::STEPS-1;
		for($i=0; $i<=$csteps; $i++) {
		    $isBigTab = $i==self::STEPS && !$this->oQuest->data['is_finished'];

			$steps[$i] = array(
				'n'   => $isBigTab?'завершение':$i+1,
				'cur' => $i==$this->step,
				'big' => $isBigTab,
			);
			if($this->edit){
				$ug = new RL_URLGenerator($this->rh->router->getRule("edit_quest"));
				$ug->setRouter($this->rh->router);
				$ug->setParams(array(
					"community_url"	=> $this->params['community_url'],
					"quest_id"		=> $this->oQuest->id,
					"quest_step"	=> $i,
				));
				$steps[$i]['url'] = $ug->generateUrl();
			}
		}
		$this->view->data['steps'] = $steps;
		$this->view->data['cur_step'] = $this->step;
		$this->view->data['display_step'] = $this->step + 1;
		if($this->edit){
			$this->view->data['edit'] = true;
			if((!$this->oQuest->data['is_finished'])&&($this->step == self::STEPS)) {
				$this->view->data['finish_btn'] = true;
			} else {
				$this->view->data['save_btn'] = true;
			}
			if($this->oQuest->data['is_published']!=1){
				$this->view->data['publish_btn'] = true;
			}
		}else{
			//кнопка далее
			if($this->step < self::STEPS-1) {
				$this->view->data['next_btn'] = true;
			} else {
				$this->view->data['save_btn'] = true;
				$this->view->data['publish_btn'] = true;
			}
		}
	}

	private function showUserList($id, $type, $gwhite=NULL, $gblack=NULL){
		$index1 = $this->model->getRightIndex($id,false,false);
		$index2 = $this->model->getRightIndex($id,false,true);
		$gindex1 = $this->model->getRightIndex($id,true,false);
		$gindex2 = $this->model->getRightIndex($id,true,true);
		$sql = "SELECT oid, login FROM ".$this->ctx->db->db_prefix."class_user WHERE oid IN (". implode(',',$this->oQuest->data[$index1]) .")";
		$users = $this->ctx->db->query($sql);
		foreach($users as $user){
			$whiteUsers[]['login'] = $user['login'];
			$whiteList[] = $user['oid'];
		}
		$white = implode(',',$whiteList);
		$sql = "SELECT oid, login FROM ".$this->ctx->db->db_prefix."class_user WHERE oid IN (". implode(',',$this->oQuest->data[$index2]) .")";
		$users = $this->ctx->db->query($sql);
		foreach($users as $user){
			$blackUsers[]['login'] = $user['login'];
			$blackList[] = $user['oid'];
		}
		$black = implode(',',$blackList);
		$result = array(
			'type'	=> $type,
			'white' => $white,
			'black' => $black,
			'whitelist' => $whiteUsers,
			'blacklist' => $blackUsers,
			'gwhite' => isset($this->oQuest->data[$gindex1]) ? $this->oQuest->data[$gindex1] : $gwhite,
			'gblack' => isset($this->oQuest->data[$gindex2]) ? $this->oQuest->data[$gindex2] : $gblack,
		);
		return $result;
	}

	private function showStep0() {
		$this->view->data['quest'] = $this->oQuest->data;
		$this->view->data['quest']['start_date'] = isset($this->oQuest->data['doc_dates'][0])
			? $this->oQuest->data['doc_dates'][0]
			: date('Y-m-d');
		$this->view->data['quest']['finish_date'] = isset($this->oQuest->data['doc_dates'][1])
			? $this->oQuest->data['doc_dates'][1]
			: self::DATE_FOREVER
			;
		$this->view->data['show_in_main_menu'] = isset($this->oQuest->data['hide_from_main_menu'])
			? !$this->oQuest->data['hide_from_main_menu']
			: 1;
	}

	private function showStep1() {
		$this->module->aa->getInfo();
		foreach($this->ctx->doctypes as $key=>$type){
			if(in_array($key, $this->doc_types)){
				if(isset($this->oQuest->data['doc_types'])){
					$checked = in_array($key,$this->oQuest->data['doc_types'])?1:0;
				}else {
					$checked = 0;
				}
				$this->view->data['quest']['types'][] = array(
					'type'=>$key,
					'typename'=>$type['typename'],
					'checked'=>$checked,
				) ;
			}
		}

		foreach($this->module->aa->acl_data['tdi_list'] as $tdi){
			$checked = in_array($tdi['id_object'],$this->oQuest->data['doc_tdi'])?1:0;
			$this->view->data['quest']['tdis'][] = array('id'=>$tdi['id_object'],
			                          'tdi_name'=>$tdi['comment'],
			                          'checked'=>$checked,
			                          ) ;
		}
		$checked = in_array(0,$this->oQuest->data['doc_tdi'])?1:0;
		$this->view->data['quest']['tdis'][] = array('id'=>0,
		                          'tdi_name'=>'Без раздела',
		                          'checked'=>$checked,
		                          ) ;

		$this->view->data['list_data'] = $this->showUserList(Model_Quest::ROLE_DOCAUTOR,'docautor', self::RP_ALL);
	}

	private function showStep2() {
		$this->view->data['userlists'] = array(
			$this->showUserList(Model_Quest::ROLE_GIVER,'giver', self::RP_MODERATOR),
			$this->showUserList(Model_Quest::ROLE_AUTOR,'autor', self::RP_ALL),
			$this->showUserList(Model_Quest::ROLE_VOTER,'voter', self::RP_ALL),
		);
	}

	private function showStep3() {
		$votes = $this->model->getVotes($this->oQuest);
		$votingsCount = COUNT($votes);
		if($votingsCount) {
			//вывести все номинации
			$forms = array();

			for($i=0; $i<$votingsCount; $i++) {
				if($votes[$i]['method'] == Model_Quest::VM_BINAR)
					$scale = 1;
				elseif($votes[$i]['variants'][1] <= 5)
					$scale = 2;
				else
					$scale = 3;
				$forms[$i] = array(
					'id'	=> $votes[$i]['vote_id'],
					'name'	=> $votes[$i]['name'],
					'scale'	=> $scale,
					'description'	=> $votes[$i]['description'],
					'error_name'	=> $votes[$i]['name']=='',
				);
			}
		} else {
			//вывести одну пустую номинацию
			$forms = array(array('id'=> 1));
		}
		$this->view->data['forms'] = $forms;

		$this->view->data['form_tpl'] = array('id'=>'_t_');
	}

	private function showStep4() {
		$this->view->data['not_finished'] = !$this->oQuest->data['is_finished'];
		$this->view->data['is_finished'] = $this->oQuest->data['is_finished'];
		$this->view->data['post_anonce'] = $this->oQuest->data['post_anonce'];
	}

	private function stepAction0() {
		$errors = array();
		$this->oQuest->data['title'] = $this->rh->POST['title'];
		$this->oQuest->data['anonce'] = $this->rh->POST['anonce'];
		$this->oQuest->data['descript'] = $this->rh->POST['descript'];
		$this->oQuest->data['doc_dates'][0] = trim($this->rh->POST['start_date']);
		$this->oQuest->data['doc_dates'][1] = trim($this->rh->POST['finish_date']);
		$hide_menu_flag = isset($this->rh->POST['post_show_in_main_menu']) ? 0 : 1;
		if ($hide_menu_flag !== $this->oQuest->data['hide_from_main_menu']) {
			$this->oQuest->data['hide_from_main_menu'] = $hide_menu_flag;
			// rebuild main menu
			$this->view->data['menu'] = $this->module->aa->getMainMenu();
		}
		if(!$this->rh->POST['title']){
			$this->view->data['ferror']['title'] = 1;
			$this->saveError = true;
		}
		if(!$this->rh->POST['descript']){
			$this->view->data['ferror']['descript'] = 1;
			$this->saveError = true;
		}
		if(!$this->checkDate($this->oQuest->data['doc_dates'][0])){
			$this->view->data['ferror']['start_date'] = 1;
			$errors['start_date'] = true;
			$this->saveError = true;
		}
		if(!$this->checkDate($this->oQuest->data['doc_dates'][1])){
			$this->view->data['ferror']['finish_date'] = 1;
			$errors['finish_date'] = true;
			$this->saveError = true;
		}
		if(!isset($errors['start_date'])&&!isset($errors['finish_date']))
		{
			if(strcmp($this->rh->POST['start_date'],$this->rh->POST['finish_date'])>=0){
				$this->view->data['ferror']['dates'] = 1;
				$this->saveError = true;
			}
		}
	}

	private function saveUserList($userType, $postId) {
		$t = $this->rh->POST['users_list_'.$postId.'_1'];
		$allowList = strlen($t)?explode(',',$t):array();
		$t = $this->rh->POST['users_list_'.$postId.'_0'];
		$deniteList = strlen($t)?explode(',',$t):array();
		//юзер не может быть одновременно в бан- а аллоw-листе
		$allowList = array_diff($allowList, $deniteList);

		$index = $this->model->getRightIndex($userType,false,false);
		$this->oQuest->data[$index] = $allowList;
		$index = $this->model->getRightIndex($userType,false,true);
		$this->oQuest->data[$index] = $deniteList;
		$index = $this->model->getRightIndex($userType,true,false);
		$this->oQuest->data[$index] = $this->rh->POST['group_'.$postId.'_1'];
		$index = $this->model->getRightIndex($userType,true,true);
		$this->oQuest->data[$index] = $this->rh->POST['group_'.$postId.'_0'];
	}

	private function stepAction1() {
		if(count($this->rh->POST['quest_cl'])==0){
			$this->view->data['ferror']['cl'] = 1;
			$this->saveError = true;
		}else{
			$this->oQuest->data['doc_types'] = array(); // cleanup
			foreach($this->rh->POST['quest_cl'] as $type){
				$this->oQuest->data['doc_types'][] = $type;
			}
		}
		if(count($this->rh->POST['quest_tdi'])==0){
			$this->view->data['ferror']['tdi'] = 1;
			$this->saveError = true;
		}else{
			$this->oQuest->data['doc_tdi'] = array();
			foreach($this->rh->POST['quest_tdi'] as $type){
				$this->oQuest->data['doc_tdi'][] = $type;
			}
		}
		$this->saveUserList(Model_Quest::ROLE_DOCAUTOR, "docautor");
	}

	private function stepAction2() {
		$this->saveUserList(Model_Quest::ROLE_GIVER, "giver");
		$this->saveUserList(Model_Quest::ROLE_AUTOR, "autor");
		$this->saveUserList(Model_Quest::ROLE_VOTER, "voter");
	}

	private function stepAction3() {
		//кол-во номинаций (-1 за счёт невидимого шаблона)
		$votingsCount = count($this->rh->POST['voting_id']) - 1;
		if($votingsCount == 0) {
			//каким-то чудом нет номинаций
			$this->saveError = true;
			return;
		}
		//получим текущие номинации (храним связь id-index)
		$votes = $this->model->getVotes($this->oQuest);
		$oldVotes = array();
		foreach($votes as $k=>$v) {
			$oldVotes[$v['vote_id']] = $k;
		}
		//сохранить номинации
		for($i=0; $i<$votingsCount; $i++) {
			$params = array(
				'name' => $this->rh->POST['voting_name'][$i],
				'description' => $this->rh->POST['description'][$i],
			);
			//номинации не могут быть безымянными
			if($params['name'] == '')
				$this->saveError = true;

			$scale = $this->rh->POST['scale'][$i];
			if($scale==1) {
				$params['method'] = Model_Quest::VM_BINAR;
			} else {
				$params['method'] = Model_Quest::VM_SCALE;
				$params['variants'] = $scale==2?array(1,5):array(1,10);
			}
			//добаление/изменени
			$id = $_POST['voting_id'][$i];
			if(isset($oldVotes[$id])) {
				$this->model->changeVote($this->oQuest, $id, $params);
				unset($oldVotes[$id]);
			}else
				$this->model->addVote($this->oQuest, $params);
		}
		//удаленные номинации
		foreach($oldVotes as $id=>$index) {
			$this->model->removeVote($this->oQuest, $id);
		}
	}

	private function stepAction4() {
		if(isset($this->rh->POST['post_is_finished']) && $this->rh->POST['post_anonce']){
			$this->oQuest->data['is_finished'] = 1;
			$this->oQuest->data['post_anonce'] = $this->rh->POST['post_anonce'];
		}elseif(!isset($this->rh->POST['post_is_finished'])){
			$this->oQuest->data['is_finished'] = 0;
			$this->oQuest->data['post_anonce'] = $this->rh->POST['post_anonce'];
		}else{
			$this->view->data['ferror']['post_anonce'] = 1;
			$this->saveError = true;
		}
	}


	public function ajax_getUsersList($nameBegin) {
		$nameBegin = addslashes($nameBegin);
		$sql = "SELECT oid, login FROM ".$this->ctx->db->db_prefix."class_user WHERE login LIKE '".$nameBegin."%' ORDER BY login LIMIT 10";
		$selectedUsers = $this->ctx->db->query($sql);
		foreach($selectedUsers as $user){
			$nItem = $this->ctx->cp->add_node("item");
			$nItem->add_node("id")->set_data($user['oid']);
			$nItem->add_node("name")->set_data($user['login']);
		}
	}

	public function ajax_getUserId($userName) {
		$sql = "SELECT oid FROM ".$this->ctx->db->db_prefix."class_user WHERE login='".$userName."' LIMIT 1";
		$user = $this->ctx->db->query($sql);
		$this->ctx->cp->add_node("name")->set_data($userName);
		if(count($user)==1) {
			//юзер существует, вернуть ID
			$this->ctx->cp->add_node("user_id")->set_data($user['oid']);
		}
	}
}
